const form = layui.form
const layer = layui.layer
form.render()

let w = {
  sex: '',
  username: '',
  mobile: '',
  page: '1',
  limit: '10',
}

// 表单提交
$('#form').on('submit', function (e) {
  e.preventDefault()
  let username = $('#username').val().trim()
  let mobile = $('#mobile').val().trim()
  let sex = $('#stateSelect').val()

  w = {
    sex,
    username,
    mobile,
    page: '1',
    limit: '10',
  }
  render()
  $('#username').val('')
  $('#mobile').val('')
})

$('#reset').on('click', () => {
  w = {
    sex: '',
    username: '',
    mobile: '',
    page: '1',
    limit: '10',
  }
  render()
})




render()
function render() {
  axios.get('/ydd_user/list', { params: w }).then(({ data: { data } }) => {
    // console.log(data);
    const strHtml = data.data.map((item, index) => {
      let { id, username, mobile, sex, birthday, icon } = item
      if (icon) {
        icon = icon.includes('http') ? icon : `http://124.223.14.236:8060/${icon}`
      } else {
        icon = ''
      }
      return `
      <tr>
        <td>${index + 1}</td>
        <td class="wx_id">${id}</td>
        <td class="wx-username">${username}</td>
        <td class="wx-phone">${mobile}</td>
        <td class="headImg">${icon ? `<img onerror=this.style.display="none" src="${icon}" class="vipavatar">` : ''}</td>
        <td class="wx_sex">${sex ? '女' : '男'}</td>
        <td class="wx_year">${birthday ? birthday : ''}</td>
        <td>
          <span class="radius edit" data-id="${id}">
            <i class="layui-icon layui-icon-edit"></i>
          </span>
          <span class="radius remove" data-id="${id}">
            <i class="layui-icon layui-icon-delete"></i>
          </span>
        </td>
      </tr>
      `
    }).join('')
    $('#tbody').html(strHtml)
    renderPage(data.count)
  })
}
// slideToggle()
$('.right_box').on('click', '.offSearch', function () {
  $('#form').slideToggle()
})


$('.refresh').click(() => {
  location.reload()
})

$('.filter_tbody').click(function (e) {
  // e.stopPropagation()
  $('.filter_box').toggle()
})

$('.filter_box').on('click', 'input', function (e) {
  e.stopPropagation()
  // const flag = $(this).prop('checked')
  const aa = +$(this).attr('data-aa')
  // console.log('aa:', aa)
  if (aa === 1) {
    $('.wx_id').toggle()
  } else if (aa === 2) {
    $('.wx-username').toggle()
  } else if (aa === 3) {
    $('.wx-phone').toggle()
  } else if (aa === 4) {
    $('.headImg').toggle()
  } else if (aa === 5) {
    $('.wx_sex').toggle()
  } else if (aa === 6) {
    $('.wx_year').toggle()
  }
})



let strHtml = `<form id="addForm" class="layui-form">
<!-- 第一行 分类名称 -->
<div class="layui-form-item openForm" id="uname">
  <label class="layui-form-label">用户名</label>
  <div class="layui-input-block">
    <input type="text" name="username" id="usname" required lay-verify="required" placeholder="请输入用户名名称" autocomplete="off"
      class="layui-input">
  </div>
</div>
<!-- 第二行 分类别名  -->
<div class="layui-form-item openForm" id="shouJi">
  <label class="layui-form-label">手机号</label>
  <div class="layui-input-block">
    <input type="text" name="mobile" required lay-verify="required" placeholder="请输入手机号"
      autocomplete="off" class="layui-input">
  </div>
</div>
<!-- 第二行 分类别名  -->
<div class="layui-form-item openForm" id="pwd">
  <label class="layui-form-label">密码</label>
  <div class="layui-input-block">
    <input type="password" name="password" required lay-verify="required" placeholder="请输入密码" autocomplete="off"
      class="layui-input">
  </div>
</div>
<div class="layui-form-item" id="sex">
  <label class="layui-form-label">性别</label>
  <div class="layui-input-block">
   <input type="checkbox" name="sex" lay-skin="switch" lay-text="女|男" value="1"> 
  </div>
</div>
<input type="file" id="file" name="icon" style="display: none;">
<div class="layui-form-item icon-upload">
  <button type="button" class="layui-btn" id="test1">
    <i class="layui-icon">&#xe67c;</i>上传图片
  </button>
</div>

<div class="image" style="display: none;"><img src="" id="Img"></div>
<!-- 第三行 按钮 -->
<div class="layui-form-item">
  <div class="layui-input-block">
    <button class="layui-btn" lay-submit lay-filter="formDemo">确认添加</button>
    <button type="reset" id="close" class="layui-btn layui-btn-primary">取消</button>
  </div>
</div>
</form>`

let addForm
$('#addData').on('click', function () {
  addForm = layer.open({
    content: strHtml, // 内容
    type: 1, // 弹出层类别
    title: '添加文章类别', // 标题
    area: ['400px', '350px'] // 定宽高
  });
  form.render('checkbox');
})

$('body').on('click', '#test1', function () {
  $('#file').click()
})
let fileUrl = ''
$('body').on('change', '#file', function () {
  if (this.files) {
    $('.image').show()
    $('.icon-upload').hide()
    const files = this.files[0]
    const fd = new FormData()
    fd.append('file', files)
    if (!files) return layer.msg('请选择图片')
    // console.log('files', files)
    axios.defaults.headers["Content-Type"] = "multipart/form-data";
    axios.post('/common/upload?type=images', fd).then(({ data: { data } }) => {
      // console.log(data.savePath);
      fileUrl = data.savePath
    })
    const imgStr = URL.createObjectURL(files)
    // console.log('imgStr:', imgStr)
    $('#Img').attr('src', imgStr)
  }
})

$('body').on('submit', '#addForm', function (e) {
  e.preventDefault()
  let $image = $(".image #Img")
  // console.log('image:', $image)
  let sex = '0'
  if ($('[name=sex]').prop('checked')) {
    sex = '1'
  }
  const fd = new FormData()
  fd.append('mobile', $('[name=mobile]').val().trim())
  fd.append('password', $('[name=password]').val().trim())
  fd.append('username', $('#usname').val().trim())
  fd.append('sex', sex)
  fd.append('icon', fileUrl)


  axios.post('/ydd_user/add', fd).then((data) => {
    // console.log(data);
    render()
    $('#addForm')[0].reset()
    layer.close(addForm)
  })

  // fd.forEach((value, name) => {
  //   console.log(value, name);
  // })

})


$('body').on('click', '#close', function () {
  layer.close(addForm)
})

let editStrHtml = `<form id="editStrForm" class="layui-form" lay-filter="editText">
<!-- 第一行 分类名称 -->
<div class="layui-form-item openForm" id="usename">
  <label class="layui-form-label">用户名</label>
  <div class="layui-input-block">
    <input type="text" name="username" id="usnname" required lay-verify="required" placeholder="请输入用户名名称" autocomplete="off"
      class="layui-input">
  </div>
</div>
<input type="text" name="id" style="display: none;">
<!-- 第二行 分类别名  -->
<div class="layui-form-item openForm" id="shouJioh">
  <label class="layui-form-label">手机号</label>
  <div class="layui-input-block">
    <input type="text" name="mobile" required lay-verify="required" placeholder="请输入手机号"
      autocomplete="off" class="layui-input">
  </div>
</div>
<!-- 第二行 分类别名  -->
<div class="layui-form-item openForm" id="psd">
  <label class="layui-form-label">密码</label>
  <div class="layui-input-block">
    <input type="password" name="password" placeholder="请输入密码" autocomplete="off"
      class="layui-input">
  </div>
</div>
<div class="layui-form-item" id="sexe">
  <label class="layui-form-label">性别</label>
  <div class="layui-input-block">
   <input type="checkbox" name="sex" lay-skin="switch" lay-text="女|男" value="1"> 
  </div>
</div>

<input type="file" class="file" style=" display: none;">
<div class="layui-form-item icon-upload">
  <button type="button" class="layui-btn" id="test2">
    <i class="layui-icon">&#xe67c;</i>上传图片
  </button>
</div>

<div class="image" style="display: none;"><img src="" id="img"></div>
<!-- 第三行 按钮 -->
<div class="layui-form-item">
  <div class="layui-input-block">
    <button class="layui-btn" lay-submit lay-filter="formDemo">确认</button>
    <button type="reset" id="closes" class="layui-btn layui-btn-primary">取消</button>
  </div>
</div>
</form>`

let editHtmlForm
$('#tbody').on('click', '.edit', function () {
  const id = $(this).attr('data-id')
  // console.log('id:', id)
  axios.get('/ydd_user/rowInfo', {
    params: { id }
  }).then(({ data: { data } }) => {
    // console.log(data);
    form.val("editText", data);
  })
  editHtmlForm = layer.open({
    content: editStrHtml, // 内容
    type: 1, // 弹出层类别
    title: '添加文章类别', // 标题
    area: ['400px', '350px'] // 定宽高
  });

  form.render('checkbox');
})
$('body').on('click', '#test2', function () {
  $('.file').click()
})

let editFiles = ''
$('body').on('change', '.file', function () {
  if (this.files) {
    $('.image').show()
    $('.icon-upload').hide()
    const files = this.files[0]
    // console.log('files:', files)
    const fd = new FormData()
    fd.append('file', files)
    if (!files) return layer.msg('请选择图片')

    axios.defaults.headers["Content-Type"] = "multipart/form-data";
    axios.post('/common/upload?type=images', fd).then(({ data: { data } }) => {
      // console.log(data.savePath);
      editFiles = data.savePath
    })
    const imgStr = URL.createObjectURL(files)
    // console.log('imgStr:', imgStr)
    $('#img').attr('src', imgStr)
  }
})

$('body').on('submit', '#editStrForm', function (e) {
  e.preventDefault()
  let sex = '0'
  if ($('[name=sex]').prop('checked')) {
    sex = '1'
  }
  const srcStr = $('#img').prop('src')
  const fd = new FormData()
  fd.append('mobile', $('[name=mobile]').val().trim())
  fd.append('password', $('[name=password]').val().trim())
  fd.append('username', $('#usnname').val().trim())
  fd.append('icon', editFiles)
  fd.append('sex', sex)
  fd.append('id', $('[name=id]').val().trim())

  axios.defaults.headers["Content-Type"] = "multipart/form-data";
  axios.post('/ydd_user/update', fd).then(({ data }) => {
    // console.log(data);
    if (data.errno !== 0) return layer.msg('修改失败')
    layer.msg('修改成功')
    render()
    $('#editStrForm')[0].reset()
    layer.close(editHtmlForm)
  })
})

$('body').on('click', '.remove', function () {
  const id = $(this).attr('data-id')
  // console.log('id:', id)
  layer.confirm('确定删除吗?', { icon: 3, title: '提示' }, function (index) {
    //do something
    axios.get('/ydd_user/del', { params: { id } }).then(({ data }) => {
      // console.log(data);
      if (data.errno !== 0) return layer.msg('删除失败')
      layer.msg('删除成功')
      render()
    })
    layer.close(index);
  });
})
// 导出按钮
function exportExcel() {
  // 获取表格数据
  const data = [['序号', 'ID', '用户名', '手机号码', '头像', '性别', '生日']];
  $('#tbody tr').each(function(index) {
    const id = $(this).find('.wx_id').text();
    const username = $(this).find('.wx-username').text();
    const mobile = $(this).find('.wx-phone').text();
    const icon = $(this).find('.headImg img').attr('src');
    const sex = $(this).find('.wx_sex').text();
    const birthday = $(this).find('.wx_year').text();
    data.push([index + 1, id, username, mobile, icon, sex, birthday]);
  });

  // 创建工作簿
  const workbook = XLSX.utils.book_new();
  const worksheet = XLSX.utils.aoa_to_sheet(data);
  XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1');

  // 导出Excel文件
  const filename = '用户列表.xlsx';
  XLSX.writeFile(workbook, filename);
}

// 分页
let laypage = layui.laypage;
function renderPage(count) {

  //执行一个laypage实例
  laypage.render({
    elem: 'page-box', //注意，这里的 test1 是 ID，不用加 # 号
    count, //数据总数，从服务端得到
    limit: w.limit, // 每条页数
    limits: [1, 2, 3, 5, 8, 10],
    curr: w.page,  // 起始页
    layout: ['count', 'limit', 'prev', 'page', 'next', 'skip'], // 自定义排版。
    jump: function (obj, first) {
      //obj包含了当前分页的所有参数，比如：
      // console.log(obj.curr); //得到当前页，以便向服务端请求对应页的数据。
      // console.log(obj.limit); //得到每页显示的条数

      // 修改pagenum值
      w.page = obj.curr
      // 修改pagesize值
      w.limit = obj.limit
      // renderCate()
      //首次不执行
      if (!first) {
        //do something
        // 发送请求
        render()
      }
    }
  });
}